package com.luntan.school.dao.impl;

import com.luntan.school.dao.CategoryDao;
import com.luntan.school.model.Category;
import com.luntan.school.util.DBUtil;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class CategoryDaolmpl implements CategoryDao {

    @Override
    public List<Category> getAllCategories() {
        try {
            Connection connection = DBUtil.getConnection();

            Statement statement = connection.createStatement();
            ResultSet resultSet = statement.executeQuery("select * from category");
            //封装结果为列表数据
            List<Category> categories = new ArrayList<>();
            while (resultSet.next()) {
                Category category = new Category();
                int id = resultSet.getInt("id");
                String name = resultSet.getString("name");
                category.setId(id);
                category.setName(name);

                categories.add(category);
            }

            connection.close();
            statement.close();
            resultSet.close();

            //返回结果
            return categories;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        CategoryDao categoryDao = new CategoryDaolmpl();
        System.out.println(categoryDao.getAllCategories());
    }
}
